require_relative "parsers/wein.cc.rb"
require_relative "parsers/avin.cc.rb"
require_relative "tools.rb"
require_relative "wine.class.rb"
require_relative "io-handlers/csv.rb"
require "csv"
require "choice"
require "logger"

$log = Logger.new(STDOUT)
$log.level = Logger::DEBUG

AVIN_STORAGE = "AVIN"

##################################################################################################
# ARGs handling
##################################################################################################
Choice.options do
    header ''
    header 'Specific options:'
	
	option :input, :required => true do
		short '-i'
		long '--input=STORAGE'
		desc 'The storage to use as input. See STORAGE description for details' 
		desc 'If the file does not exist, the program will exit'
    end
	
	option :output, :required => true do
		short '-o'
		long '--output=STORAGE'
		desc 'The storage to use as output. See STORAGE description for details'  
		desc 'If the file does not exist, it will be created'		
    end
	
	option :avinkey, :required => false do
		short '-avin'
		long '--avinkey=YOUR_AVIN_KEY'
		desc 'Your AVIN.CC API-Key'     
    end

	separator ''
    separator 'Common options: '
	separator '[STORAGE] is either a filename (such as test.cvs) or the String #{AVIN_STORAGE} if you want to use avin.cc as storage.'
end

inputHandler = nil
outputHandler = nil


if Choice.choices.input != AVIN_STORAGE then
	if !File.exists?(Choice.choices.input) then
		puts "Could not find inputfile"
		exit
	end
	inputHandler = CsvHandler.new(Choice.choices.input)
else
	puts "AVIN HANDLER IS CURRENTLY not implemented"
end

if Choice.choices.output != AVIN_STORAGE then
	outputHandler = CsvHandler.new(Choice.choices.output)
else
	puts "AVIN HANDLER IS CURRENTLY not implemented"
end

##################################################################################################
# Here we start the actual update code
##################################################################################################
newWines = Array.new(0)
oldWines = inputHandler.getWines
# read CSV
oldWines.each do |wine|
	if wine.needsLookup then	
		$log.info "CSV: Looking for updates for EAN: " + wine.ean
		$log.debug "Starting searches"
  
		newWines += WineCc.getWines(wine.ean)
  
		$log.info "Added wine to internal database"
	else
		$log.debug "Wine update skipped as it is not needed for wine '#{wine.name}'"
  end
end 

$log.info "We found " + newWines.size.to_s + " wines"

# write cvs
$log.info "Start writing csv"

outputHandler.saveWines(newWines.concat(oldWines))

$log.info "End writing csv"


